import {
    Controller,
    Post,
    UseInterceptors,
    UploadedFile,
    BadRequestException,
} from '@nestjs/common';
import { FileInterceptor } from '@nestjs/platform-express';
import { UploadService } from './upload.service';
import { diskStorage } from 'multer';
import { extname, join } from 'path';
import { existsSync, mkdirSync } from 'fs';

@Controller('upload')
export class UploadController {
    constructor(private readonly uploadService: UploadService) { }

    /**
     * 上传图片
     */
    @Post('image')
    @UseInterceptors(
        FileInterceptor('file', {
            storage: diskStorage({
                destination: (req, file: Express.Multer.File, cb: (error: Error | null, destination: string) => void) => {
                    const uploadPath = join(process.cwd(), 'uploads', 'images');
                    // 确保目录存在
                    if (!existsSync(uploadPath)) {
                        mkdirSync(uploadPath, { recursive: true });
                    }
                    cb(null, uploadPath);
                },
                filename: (req, file: Express.Multer.File, cb: (error: Error | null, filename: string) => void) => {
                    // 生成唯一文件名：时间戳 + 随机数 + 原始扩展名
                    const uniqueSuffix =
                        Date.now() + '-' + Math.round(Math.random() * 1e9);
                    const ext = extname(file.originalname);
                    cb(null, `${uniqueSuffix}${ext}`);
                },
            }),
            limits: {
                fileSize: 10 * 1024 * 1024, // 10MB
            },
            fileFilter: (req, file: Express.Multer.File, cb: (error: Error | null, acceptFile: boolean) => void) => {
                // 只允许图片格式
                const allowedMimes = [
                    'image/jpeg',
                    'image/jpg',
                    'image/png',
                    'image/gif',
                    'image/webp',
                ];
                if (allowedMimes.includes(file.mimetype)) {
                    cb(null, true);
                } else {
                    cb(
                        new BadRequestException(
                            '不支持的文件格式，仅支持 JPEG、PNG、GIF、WebP',
                        ) as Error,
                        false,
                    );
                }
            },
        }),
    )
    async uploadImage(@UploadedFile() file: Express.Multer.File) {
        if (!file) {
            throw new BadRequestException('请选择要上传的图片');
        }

        return this.uploadService.uploadFile(file, 'image');
    }

    /**
     * 上传视频
     */
    @Post('video')
    @UseInterceptors(
        FileInterceptor('file', {
            storage: diskStorage({
                destination: (req, file: Express.Multer.File, cb: (error: Error | null, destination: string) => void) => {
                    const uploadPath = join(process.cwd(), 'uploads', 'videos');
                    // 确保目录存在
                    if (!existsSync(uploadPath)) {
                        mkdirSync(uploadPath, { recursive: true });
                    }
                    cb(null, uploadPath);
                },
                filename: (req, file: Express.Multer.File, cb: (error: Error | null, filename: string) => void) => {
                    // 生成唯一文件名：时间戳 + 随机数 + 原始扩展名
                    const uniqueSuffix =
                        Date.now() + '-' + Math.round(Math.random() * 1e9);
                    const ext = extname(file.originalname);
                    cb(null, `${uniqueSuffix}${ext}`);
                },
            }),
            limits: {
                fileSize: 100 * 1024 * 1024, // 100MB
            },
            fileFilter: (req, file: Express.Multer.File, cb: (error: Error | null, acceptFile: boolean) => void) => {
                // 只允许视频格式
                const allowedMimes = [
                    'video/mp4',
                    'video/mpeg',
                    'video/quicktime',
                    'video/x-msvideo',
                    'video/webm',
                ];
                if (allowedMimes.includes(file.mimetype)) {
                    cb(null, true);
                } else {
                    cb(
                        new BadRequestException(
                            '不支持的文件格式，仅支持 MP4、MPEG、MOV、AVI、WebM',
                        ) as Error,
                        false,
                    );
                }
            },
        }),
    )
    async uploadVideo(@UploadedFile() file: Express.Multer.File) {
        if (!file) {
            throw new BadRequestException('请选择要上传的视频');
        }

        return this.uploadService.uploadFile(file, 'video');
    }
}

